package com.stars.empoly.utils

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.Toast
import coil.load
import com.qmuiteam.qmui.kotlin.onClick
import com.qmuiteam.qmui.layout.QMUIFrameLayout
import com.qmuiteam.qmui.skin.QMUISkinValueBuilder
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.qmuiteam.qmui.widget.QMUIRadiusImageView
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.qmuiteam.qmui.widget.popup.QMUIPopup
import com.qmuiteam.qmui.widget.popup.QMUIPopups
import com.stars.empoly.R
import com.yanzhenjie.permission.Action
import com.yanzhenjie.permission.AndPermission
import com.trailer.base.utils.UiUtils
import com.zhy.http.okhttp.OkHttpUtils
import com.zhy.http.okhttp.callback.FileCallBack
import okhttp3.Call
import java.io.File
import java.io.FileNotFoundException
import java.util.*

/**
 * 分享
 *
 *on 2020/9/21
 */
object  PopuShareWxUtils {

    var chose = 1
    private const val title = "分享"
    var tipDialog: QMUITipDialog? = null
    private var downimg: String? = null
    private val uriArrayList = ArrayList<Uri>() //下载到本地的图片的集合
    fun show(context: Context, url: String, view: View){

        var mNormalPopup = QMUIPopups.fullScreenPopup(context)
        val builder: QMUISkinValueBuilder = QMUISkinValueBuilder.acquire()
        val frameLayout = QMUIFrameLayout(context)
        //自定义布局
        val layoutInflater = context?.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        var layout = layoutInflater.inflate(R.layout.item_wx_share, null)

        val img: QMUIRadiusImageView =layout.findViewById(R.id.img)
        val ivShareOne:ImageView=layout.findViewById(R.id.iv_share_one)
        val ivShareTwo:ImageView=layout.findViewById(R.id.iv_share_two)
        val ivSave:ImageView=layout.findViewById(R.id.iv_save)
        val ivClose:ImageView=layout.findViewById(R.id.iv_close)

        val params = img.getLayoutParams()

        val display = (context as Activity).windowManager.defaultDisplay
        val screenWidth = display.width
        params.width = screenWidth - UiUtils.dp2Px(context, 60f)
      //  params.height = (((screenWidth - UiUtils.dp2Px(context, 60f)) * 1.6).toInt())
        params.height=screenWidth - UiUtils.dp2Px(context, 60f)

        img.layoutParams = params

        img.load(url)

        ivShareOne.onClick{
            //分享给好友
            chose = 1
            setShareImages(context, url)
            mNormalPopup.dismiss()


        }
        ivShareTwo.onClick{

            //分享给朋友圈
            chose = 2
            setShareImages(context, url)
            mNormalPopup.dismiss()

        }

        ivClose.onClick {
            mNormalPopup.dismiss()
        }

        ivSave.onClick {

            //保存图片到本地
            saveImageToGallery(context, url)

            mNormalPopup.dismiss()
        }


        builder.release();

        val size= QMUIDisplayHelper.getScreenWidth(context)


        val lp: FrameLayout.LayoutParams = FrameLayout.LayoutParams(size,
                FrameLayout.LayoutParams.WRAP_CONTENT)
        frameLayout.addView(layout, lp)

        mNormalPopup.addView(frameLayout)
        mNormalPopup.onDismiss() {
        }

        mNormalPopup.dismissIfOutsideTouch(false)
        mNormalPopup.animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER)
        mNormalPopup.show(view)


    }


    /**
     * 保存到系统相册
     */
    @SuppressLint("WrongConstant")
    fun saveImageToGallery(context: Context, url: String) {
        AndPermission.with(context)
                .runtime()
                .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA
                )
                .onGranted(Action<List<String?>?>

                {
                    setSaveImg(context, url)
                }
                ).start()
    }

    fun setSaveImg(context: Context, url: String) {

        var tipDialog = QMUITipDialog.Builder(context)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在保存图片...")
                .create()


        Thread(Runnable {
            val bitmap: Bitmap = SaveLocalUtils.returnBitMap(url)
            SaveLocalUtils.saveBitmap(context, bitmap, "loc" + System.currentTimeMillis() + ".png")
            //                SaveLocalUtils.saveBmp2Gallery(
//                        getContext(), bitmap,
//                        "loc" + System.currentTimeMillis());
            (context as Activity).runOnUiThread {
                tipDialog!!.dismiss()
                Toast.makeText(context, "图片已保存在手机相册下！", Toast.LENGTH_LONG).show()
                //Toasts.toast(context, "图片已保存在相册CANDYIMG文件夹下！");

            }
        }).start()
    }


    fun setShareImages(context: Context, url: String) {
        tipDialog = QMUITipDialog.Builder(context)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在保存图片...")
                .create()


        //下载图片
        startDownImg(url, context)

    }

    /**
     * @param photoPathL 下载图片
     */
    private fun startDownImg(photoPathL: String, con: Context) {

        //先下载图片
        try {
            okHttpSaveImg(photoPathL, 1, con)

        }catch (e:Exception){
            Log.e("-shy-", "e=: "+e );
        }

    }

    private fun okHttpSaveImg(imgUrl: String, position: Int, con: Context?) {


        val filePath: String = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            con!!.filesDir.absolutePath
        } else {
            getSDPath() + "/revoeye/"
        }
        if (con == null) {
            // Toasts.toast(con, con.getString(R.string.action_share)+con.getString(R.string.fail)+con.getString(R.string.the_comma)+con.getString(R.string.please_share_it_later));
            return
        }
        OkHttpUtils
                .get()
                .url(imgUrl)
                .build() //
                .execute(object : FileCallBack(filePath, System.currentTimeMillis().toString() + "empoly.jpg" //
                ) {
                    override fun onError(call: Call, e: Exception, id: Int) {
                        if (con != null) {
                        }
                    }

                    override fun onResponse(response: File, id: Int) {
                        if (con != null) {
                            if (response != null) {
                                var mUri: Uri? =null
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                                    /**Android 7.0以上的方式 */
                                    if (con != null) {
                                        try {
                                            var  url=insertImageToSystem(con, response.absolutePath)
                                            if(!TextUtils.isEmpty(url)){
                                                mUri= Uri.parse(url)
                                            }
                                        }catch (e:java.lang.Exception){

                                        }

                                    } else {
                                        return
                                    }

                                }else{
                                    mUri=Uri.fromFile(response)
                                }
                                if(mUri==null){
                                    return
                                }
                               //uriArrayList.add(mUri);
                                downimg = mUri.toString()
                                if (uriArrayList.size > 0) {
                                    uriArrayList.clear()
                                }
                                uriArrayList.add(Uri.parse(downimg))
                                if (con != null) {
                                    share(con)
                                }
                            }
                        }
                    }
                })
    }


    private fun share(context: Context) {


        tipDialog!!.dismiss()

        if (chose == 1) { //微信好友
            val uriToImage = Uri.parse(downimg)

            //图片
            val shareIntent = Intent()
            //发送图片到朋友圈
            //ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
            //发送图片给好友。
            val comp = ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI")
            shareIntent.component = comp
            shareIntent.action = Intent.ACTION_SEND
            shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage)
            shareIntent.type = "image/jpeg"
            context.startActivity(Intent.createChooser(shareIntent, title))


        }
        if (chose == 2) { //微信朋友圈
            val componentName = ComponentName("com.tencent.mm",
                    "com.tencent.mm.ui.tools.ShareToTimeLineUI")
            var intent = Intent()
            intent.component = componentName
            intent.type = "image/*"
            if (uriArrayList.size > 1) {
                intent.action = Intent.ACTION_SEND_MULTIPLE
                intent.putExtra(Intent.EXTRA_STREAM, uriArrayList) //图片数据（支持本地图片的Uri形式）
            } else if (uriArrayList.size == 1) {
                intent.action = Intent.ACTION_SEND
                intent.putExtra(Intent.EXTRA_STREAM, uriArrayList[0]) //图片数据（支持本地图片的Uri形式）
            }
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                    or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            intent.putExtra("Kdescription", title)
            intent.putExtra(Intent.EXTRA_TEXT, title) //正常使用的文字

            context.startActivity(intent)


        }
    }



    private fun insertImageToSystem(context: Context, imagePath: String): String? {
        var url: String? = ""
        try {

            // url = MediaStore.Images.Media.insertImage(context.getContentResolver(), imagePath, SHARE_PIC_NAME, "你对图片的描述");
            url = MediaStore.Images.Media.insertImage(context.contentResolver, imagePath, "IMG" + Calendar.getInstance().time, null)

           // url = MediaStore.Images.Media.insertImage(context.contentResolver, imagePath, SHARE_PIC_NAME, "你对图片的描述")
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            Log.e("shy", "Exception1=$e")
        }
        return url
    }

    fun getSDPath(): String? {
        var sdDir: File? = null
        val sdCardExist = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED //判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory() //获取跟目录
        }
        return sdDir.toString()
    }



}
